#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include "cJSON.h"

#define HOST "api.seniverse.com"
#define IP "fill your IP" //填入你服务器的IP
#define PORT 80
#define KEY "fill your API" //填入你的心知天气的API

int send_request(const char *request, char *response, size_t max_len) {
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) return -1;

    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(PORT);
    addr.sin_addr.s_addr = inet_addr(IP);

    if (connect(sockfd, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
        close(sockfd);
        return -2;
    }

    write(sockfd, request, strlen(request));
    int total = 0, ret;
    while ((ret = read(sockfd, response + total, max_len - 1 - total)) > 0) {
        total += ret;
        if (total >= max_len - 1) break;
    }
    response[total] = '\0';
    close(sockfd);
    return 0;
}

char* extract_body(char *http_response) {
    char *body = strstr(http_response, "\r\n\r\n");
    return body ? body + 4 : NULL;
}

void query_air_quality(const char *location) {
    char request[1024], response[8192];
    snprintf(request, sizeof(request),
        "GET /v3/air/now.json?key=%s&location=%s&language=zh-Hans&scope=all HTTP/1.1\r\n"
        "Host: %s\r\n"
        "Connection: close\r\n\r\n",
        KEY, location, HOST);

    if (send_request(request, response, sizeof(response)) != 0) {
        printf("❌ 无法连接空气质量服务器。\n");
        return;
    }

    char *body = extract_body(response);
    if (!body) {
        printf("❌ 无有效AQI响应。\n");
        return;
    }

    cJSON *root = cJSON_Parse(body);
    if (!root) {
        printf("❌ AQI JSON解析失败。\n");
        return;
    }

    cJSON *results = cJSON_GetObjectItem(root, "results");
    cJSON *first = cJSON_GetArrayItem(results, 0);
    if (!first) {
        cJSON_Delete(root);
        printf("❌ 未找到空气质量数据。\n");
        return;
    }

    cJSON *air = cJSON_GetObjectItem(first, "air");
    cJSON *city = cJSON_GetObjectItem(air, "city");

    cJSON *aqi = cJSON_GetObjectItem(city, "aqi");
    cJSON *pm25 = cJSON_GetObjectItem(city, "pm25");
    cJSON *quality = cJSON_GetObjectItem(city, "quality");
    cJSON *desc = cJSON_GetObjectItem(city, "description");
    cJSON *zh_desc = desc ? cJSON_GetObjectItem(desc, "zh") : NULL;

    if (aqi && pm25 && quality) {
        printf("\n-- 空气质量信息 --\n");
        printf(" 空气质量指数AQI：%s\n", aqi->valuestring);
        printf(" PM2.5：%s\n", pm25->valuestring);
        printf(" 空气等级：%s\n", quality->valuestring);
        if (zh_desc && zh_desc->valuestring)
            printf(" 空气说明：%s\n", zh_desc->valuestring);
    }

    cJSON_Delete(root);
}

void query_weather(const char *location) {
    char request[1024], response[8192];
    snprintf(request, sizeof(request),
        "GET /v3/weather/now.json?key=%s&location=%s&language=zh-Hans&unit=c HTTP/1.1\r\n"
        "Host: %s\r\n"
        "Connection: close\r\n\r\n",
        KEY, location, HOST);

    if (send_request(request, response, sizeof(response)) != 0) {
        printf("❌ 无法连接天气服务器。\n");
        return;
    }

    char *body = extract_body(response);
    if (!body) {
        printf("❌ 无有效天气响应。\n");
        return;
    }

    cJSON *root = cJSON_Parse(body);
    if (!root) {
        printf("❌ 天气 JSON解析失败。\n");
        return;
    }

    cJSON *results = cJSON_GetObjectItem(root, "results");
    cJSON *first = cJSON_GetArrayItem(results, 0);
    if (!first) {
        printf("未找到城市/区域天气信息。\n");
        cJSON_Delete(root);
        return;
    }

    cJSON *loc = cJSON_GetObjectItem(first, "location");
    cJSON *name = cJSON_GetObjectItem(loc, "name");
    cJSON *now = cJSON_GetObjectItem(first, "now");
    cJSON *text = cJSON_GetObjectItem(now, "text");
    cJSON *temp = cJSON_GetObjectItem(now, "temperature");

    if (name && text && temp) {
        printf("\n📍 城市/区域：%s\n🌤 天气：%s\n🌡 温度：%s℃\n",
               name->valuestring, text->valuestring, temp->valuestring);
    }

    cJSON_Delete(root);

    // 空气质量追加调用
    query_air_quality(location);
}

int main() {
    const char *default_city = "conghua";

    printf("显示当前城市：从化 的天气和空气质量：\n");
    query_weather(default_city);

    char input[64];
    while (1) {
        printf("\n请输入其他城市/区域（支持拼音，如 'beijing' 或 'guangzhou,tianhe'，回车退出）：");
        if (!fgets(input, sizeof(input), stdin)) break;
        input[strcspn(input, "\n")] = '\0';
        if (strlen(input) == 0) break;
        query_weather(input);
    }

    printf("退出天气查询。\n");
    return 0;
}
